/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoginPanel.java
 *
 * Created on May 7, 2011, 12:55:45 AM
 */
package uploadphotobucket.view;

import java.awt.Cursor;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import javax.swing.JOptionPane;
import org.json.JSONObject;
import uploadphotobucket.action.ActionPhotobucket;
import utils.AnalyzeAlbum;
import utils.Browser;
import utils.Message;
import utils.Utils;
import utils.SharedObject;

/**
 *
 * @author banhbaochay
 */
public class LoginPanel extends javax.swing.JPanel {

    /**
     * 
     * @param sharedMap
     * @param locale  
     */
    public LoginPanel(SharedObject sharedMap, Locale locale) {
        this.locale = locale;
        Message.initialize(locale);
        this.sharedMap = sharedMap;
        this.oauthConsumerKey = (String) sharedMap.getOauthConsumerKey();
        this.oauthConsumerSecret = (String) sharedMap.getOauthConsumerSecret();
        action = new ActionPhotobucket(oauthConsumerKey, oauthConsumerSecret);
        this.browser = (Browser) sharedMap.getBrowser();
        initComponents();
    }// end constructor

    /**
     * Change language of panel by locale
     */
    public void changeLanguage() {
        ResourceBundle rs = ResourceBundle.getBundle("resourcebundle.LoginPanel", locale);
        getReqButton.setToolTipText(rs.getString("LoginPanel.getReqButton.toolTipText"));
        goButton.setToolTipText(rs.getString("LoginPanel.goButton.toolTipText"));
        accessButton.setToolTipText(rs.getString("LoginPanel.accessButton.toolTipText"));
        resultWebLabel.setText(rs.getString("LoginPanel.resultWebLabel.text"));
    }// end changeLanguage method

    /**
     * Call when locale is changed by another form
     * @param locale
     */
    public void localeChanged(Locale locale) {
        this.locale = locale;
        Message.initialize(locale);
    }// end localeChanged method

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        goButton = new javax.swing.JButton();
        accessButton = new javax.swing.JButton();
        getReqButton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        resultArea = new javax.swing.JTextArea();
        resultWebLabel = new javax.swing.JLabel();

        setLayout(new java.awt.GridBagLayout());

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("resourcebundle/LoginPanel"); // NOI18N
        goButton.setText(bundle.getString("LoginPanel.goButton.text")); // NOI18N
        goButton.setToolTipText(bundle.getString("LoginPanel.goButton.toolTipText")); // NOI18N
        goButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                goButtonActionPerformed(evt);
            }
        });

        accessButton.setText(bundle.getString("LoginPanel.accessButton.text")); // NOI18N
        accessButton.setToolTipText(bundle.getString("LoginPanel.accessButton.toolTipText")); // NOI18N
        accessButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                accessButtonActionPerformed(evt);
            }
        });

        getReqButton.setText(bundle.getString("LoginPanel.getReqButton.text")); // NOI18N
        getReqButton.setToolTipText(bundle.getString("LoginPanel.getReqButton.toolTipText")); // NOI18N
        getReqButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                getReqButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(getReqButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                .addComponent(goButton)
                .addGap(42, 42, 42)
                .addComponent(accessButton)
                .addGap(31, 31, 31))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(getReqButton)
                    .addComponent(goButton)
                    .addComponent(accessButton))
                .addContainerGap())
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(20, 20, 20, 20);
        add(jPanel1, gridBagConstraints);

        resultArea.setColumns(20);
        resultArea.setLineWrap(true);
        resultArea.setRows(5);
        resultArea.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                resultAreaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(resultArea);

        resultWebLabel.setText(bundle.getString("LoginPanel.resultWebLabel.text")); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(resultWebLabel)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(16, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addComponent(resultWebLabel))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(20, 20, 20, 20);
        add(jPanel2, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

    private void getReqButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getReqButtonActionPerformed
        // TODO add your handling code here:
        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        resultArea.setText("");
//        RequestArgument args = new RequestArgument(oauthConsumerKey, oauthConsumerSecret);
//        action.initRequest(args);
        try {
            consumerJSON = action.request();
            resultArea.setText("http://photobucket.com/apilogin/login?oauth_token="
                    + consumerJSON.get("oauth_token"));

        } catch (Exception ex) {
            resultArea.setText(ex.getMessage());
        }
        this.setCursor(null);
}//GEN-LAST:event_getReqButtonActionPerformed

    private void goButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goButtonActionPerformed
        // TODO add your handling code here:
        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        String url = resultArea.getText();
        try {
            browser.browseURL(url);
        } catch (UnsupportedOperationException e) {
            JOptionPane.showMessageDialog(null, Message.NOT_SUPPORTED_BROWSER(),
                    "Warning", JOptionPane.WARNING_MESSAGE);
        } catch (IOException ex) {
            resultArea.setText(ex.getMessage());
        }// end try
        this.setCursor(null);
}//GEN-LAST:event_goButtonActionPerformed

    private void resultAreaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resultAreaMouseClicked
        // TODO add your handling code here:
        resultArea.selectAll();
        Utils.setClipboard(resultArea.getSelectedText());
}//GEN-LAST:event_resultAreaMouseClicked

    private void accessButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_accessButtonActionPerformed
        // TODO add your handling code here:
        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        //        Check condition for access
        if (consumerJSON == null) {
            JOptionPane.showMessageDialog(null, Message.NEED_REQUEST(), "Error",
                    JOptionPane.ERROR_MESSAGE);
        } else {
            try {
                userJSON = action.access(consumerJSON);
                sharedMap.addUserJSON(userJSON);
            } catch (Exception ex) {
                this.setCursor(null);
                resultArea.setText(ex.getMessage());
                return;
            }// end try catch
            if (userJSON.has("oauth_token")) {
                resultArea.setText(Message.ACCESS_DONE());
            } else {
                resultArea.setText(Message.ACCESS_FAILED());
                JOptionPane.showMessageDialog(null, Message.NOT_PERMISSION(), "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
            try {
                JSONObject json = action.getAlbum(userJSON);
                if (json.has("status")) {
                    if (json.optString("status").equalsIgnoreCase("ok")) {
                        albumMap = AnalyzeAlbum.getAlbumMap(json.optJSONObject("content").optJSONObject("album"));
                        sharedMap.addAlbumMap(albumMap);
                    } else {
                        JOptionPane.showMessageDialog(null, Message.NOT_GET_ALBUM_LIST() + "\nCode:" + json.toString(), "Error",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }// end if json.has("status")
            } catch (Exception ex) {
                this.setCursor(null);
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }// end consumerJSON == null

        this.setCursor(null);
}//GEN-LAST:event_accessButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton accessButton;
    private javax.swing.JButton getReqButton;
    private javax.swing.JButton goButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea resultArea;
    private javax.swing.JLabel resultWebLabel;
    // End of variables declaration//GEN-END:variables
    private String oauthConsumerKey;
    private String oauthConsumerSecret;
    private ActionPhotobucket action;
    /**
     * Save information for program access to web
     *   - oauth_token
     *   - oauth_token_secret
     */
    private JSONObject consumerJSON;
    private Browser browser;
    /**
     * Save information about user:
     *   - subdomain
     *   - username
     *   - oauth_token
     *   - oauth_token_secret
     */
    private JSONObject userJSON;
    /**
     * Store all album in account
     */
    private Map albumMap;
    private SharedObject sharedMap;
    private Locale locale;
}// end LoginPanel class
